<?php

class Controller_Account extends Controller_Website
{

    public function before() {
        parent::before();
        $this->mod = Model::factory('directory');
        $this->man = Model::factory('manager');
        $this->section = 'account';
        $this->template->controller=Request::$controller;
        //        $this->addStyle('/styles/cusel.css');
        //        $this->addScript('/scripts/loadSelect.js');
        if (!isset($_SESSION['identity'])){
            $this->response->redirect('/signin/');
        }
        $this->template->content = new View('account/index');
        $this->template->content->controller=Request::$controller;
//        $this->template->content->childTemplate=new View('account/normal');//Можна змінити account_main_text_content
    }

	public function actionIndex()
	{
        $this->response->redirect(Request::$controller.'orders/');
	}
    public function actionOrders()
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        $this->template->content->childTemplate=new View('account/orders');
        $this->template->content->childTemplate->orders=$this->man->getOrders($_SESSION['identity']['email']);
    }
    public function actionOrder($id=null)
    {
        if(!$id){
            echo'OH NO';
            $this->response->redirect(Request::$controller.'orders/');
            die();
        }
        $id=(int)$id;
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        $this->template->content->childTemplate=new View('account/order');
        $this->template->content->childTemplate->items=$this->man->getOrderId($id);
//        system::dump($this->template->content->childTemplate->order);exit();
    }
    public function actionReturns()
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
    }
    public function actionWait()
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
    }
    public function actionInvitations()
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        $this->template->content->childTemplate=new View('account/invite');
        $this->template->content->childTemplate->invitations=$this->man->getInvitations($_SESSION['identity']['id']);
    }
    public function actionInvitationsAdd()
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        $form = new Form('contact');
        $form->text('email', 'Email Address:')->rule('email')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->submit('submit', 'Send');
        if(Request::$method == 'POST') {
            if($form->validate()) {
                $values = $form->getValues();
                if($_SESSION['identity']['email']==$values['email']){
                    echo'<script type="text/javascript">alert(\'Very funny :)\');</script>';
                    $this->response->redirect(Request::$controller.'invitations/');
                }
                $this->man->newInvitation($_SESSION['identity']['id'],$values['email']);
                $this->response->redirect(Request::$controller.'invitations/');
            }
        }
        $this->template->content->form=$form;

    }
    public function actionSettings()
    {
        $userData=$this->man->selectUser($_SESSION['identity']['id']);
        $memberData=$this->man->selectMember($_SESSION['identity']['id']);
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        $form = new Form('contact');
        $form->text('name1', 'First Name:',isset($memberData['name1'])?$memberData['name1']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->text('name2', 'Last Name:',isset($memberData['name2'])?$memberData['name2']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->text('email', 'Email Address:', $userData['email'])->rule('email')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->select('gender', array('--Select--','Female','Male'), 'Gender:',isset($memberData['gender'])?$memberData['gender']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->password('passwd', 'Current Password:',null)->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->password('passwd1', 'New Password:',null)->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->password('passwd2', 'Verify Password:',null)->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->submit('submit', 'Save');
        if(Request::$method == 'POST') {
            if($form->validate()) {
                $values = $form->getValues();
                //system::dump($values);exit();
                if($values['name1']<>$memberData['name1']||$values['name2']<>$memberData['name2']||$values['gender']<>$memberData['gender']){
                    $this->man->setMember($_SESSION['identity']['id'],$values['name1'],$values['name2'],$values['gender']);
                }
                if($values['email']<>$userData['email']||!empty($values['passwd'])||!empty($values['passwd1'])||!empty($values['passwd2'])){
                    if((!empty($values['passwd']))&&(!empty($values['passwd1']))&&($values['passwd1']==$values['passwd2'])&&($values['passwd']<>$values['passwd1'])){
                        $newPassword=$values['passwd1'];
                        $oldPassword=$values['passwd'];
                    }
                    $ans = Auth::getInstance()->editMail($_SESSION['identity']['id'],$values['email'],isset($newPassword)?$newPassword:null,isset($oldPassword)?$oldPassword:null);
                    echo'<script type="text/javascript">alert("'.$ans.'")</script>';
                }$form->elements['passwd']->value='';$form->elements['passwd1']->value='';$form->elements['passwd2']->value='';
            } else {
                if(isset($_POST['employee'])) {
                    $this->autoRender = false;
                    $this->response->setHeader('Content-Type', 'application/json');
                    $this->response->body = json_encode(array('success' => 've'));
                }$form->elements['passwd']->value='';$form->elements['passwd1']->value='';$form->elements['passwd2']->value='';
            }

        }
        $this->template->content->form=$form;
    }
    public function actionShipping()
    {
        $this->template->content->childTemplate=new View('account/shipping');
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        $this->template->content->childTemplate->controller=Request::$controller;
        $this->template->content->childTemplate->adresses=$adresses=$this->man->getShipping($_SESSION['identity']['id']);
//        system::dump($adresses);exit();
        if(empty($adresses)){$this->response->redirect(Request::$controller.'change/');}else{$this->template->content->adress=$adresses;
        }
    }
    public function actionDropship($id)
    {
        $this->man->dropShipping($id,$_SESSION['identity']['id']);
        $this->response->redirect(Request::$controller.'shipping/');

    }
    public function actionPrimaryship($id)
    {
        $this->man->setPrimaryShipping($id,$_SESSION['identity']['id']);
        $this->response->redirect(Request::$controller.'shipping/');
    }
    public function actionChange($id=null)
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        $memberData=$this->man->selectMember($_SESSION['identity']['id']);
        $populateData=isset($id)?$this->man->getShippingId($id,$_SESSION['identity']['id']):array();
        if(!isset($firstName)&&isset($populateData['name1'])){
            $firstName=$populateData['name1'];
        }elseif(!isset($firstName)&&isset($memberData['name1'])){
            $firstName=$memberData['name1'];
        }else{
            $firstName='';
        }
        if(!isset($secondName)&&isset($populateData['name2'])){
            $secondName=$populateData['name2'];
        }elseif(!isset($secondName)&&isset($memberData['name2'])){
            $secondName=$memberData['name2'];
        }else{
            $secondName='';
        }
        $form = new Form('shipping');
        $form->text('name1', 'First Name:',$firstName)->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->text('name2', 'Last Name:',$secondName)->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->text('country', 'Country:',isset($populateData['country'])?$populateData['country']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->text('city', 'City:',isset($populateData['city'])?$populateData['city']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->select('customerState', array_merge(array('' => ''), Text::$states), 'State:',isset($populateData['state'])?$populateData['state']:'');
        $form->text('adress', 'Adress:',isset($populateData['street'])?$populateData['street']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->text('postal', 'Zip-code:',isset($populateData['postal'])?$populateData['postal']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');
        $form->text('phone', 'Phone:',isset($populateData['phone'])?$populateData['phone']:'')->rule('required')->rule('maxLength', 32)->attribute('style', 'width: 250px');

        $form->submit('submit', 'Save');
        if(Request::$method == 'POST'&&(!isset($id))) {
            if($form->validate()) {
                $values = $form->getValues();
                $this->man->addShipping($_SESSION['identity']['id'],$values['name1'],$values['name2'],$values['country'],$values['adress'],$values['city'],$values['customerState'],$values['postal'],$values['phone'],'0');
                $this->response->redirect(Request::$controller.'shipping/');
            }
        }elseif(Request::$method == 'POST'&&(isset($id))){
            if($form->validate()) {
                $values = $form->getValues();
                $this->man->updateShipping($id,$_SESSION['identity']['id'],$values['name1'],$values['name2'],$values['country'],$values['adress'],$values['city'],$values['customerState'],$values['postal'],$values['phone'],'0');
                $this->response->redirect(Request::$controller.'shipping/');
            }
        }
        $this->template->content->form=$form;
    }
    public function actionPayment()
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
    }
    public function actionCredits($check=null)
    {
        $memberData=$this->man->selectMember($_SESSION['identity']['id']);
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
        if($check){
            $this->man->updateCredits($_SESSION['identity']['id'],$_SESSION['identity']['email']);
            $this->response->redirect(Request::$controller.'credits/');
        }
        $text='';
        $text.='You ballance:'.$memberData['ballance'].' uah<br />';
        $text.='<a href="update/">Update bonus</a>';
        $this->template->content->text1=$text;
    }
    public function actionSpecials()
    {
        $this->template->content->category=strtolower(substr(__FUNCTION__, 6));
    }

    public function actionFavourite(){
        $this->autoRender = FALSE;
        if(Request::$isAjax)
        {
            $response = array();
            if(!empty($_SESSION['identity']))
            {
                $size = trim($_POST['size']);
                $userId = $_SESSION['identity']['id'];
                $result = $this->manager->addFavouriteSize($userId,$size);
                if($result){
                    $response['success'] = 'Congratulations!Size has been added';
                }
                else
                {
                    $response['error'] = 'Size hasnt been added';
                }
            }
            else
            {
                $response['error'] = 'You are not logged in.Only members can do this';
            }

            $this->response->setHeader('Content-Type', 'application/json');
            $this->response->body = json_encode($response);
        }
    }

}
